package com.rw.coco.data.data.mapper;

import com.rw.coco.api.data.model.GroupModel;
import com.rw.coco.api.data.persistence.simple.SimpleGroupMapper;
import com.rw.coco.data.data.bean.FileGroupModel;
import com.rw.coco.data.data.util.BeanUtil;
import com.rw.tool.util.io.FileIOUtil;
import com.rw.tool.util.io.file.BeanFile;
import com.rw.tool.util.json.JsonUtil;

import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class FileGroupMapper extends SimpleGroupMapper {
    private static final String GROUP_PATH = "\\group\\";

    private final BeanFile<FileGroupModel> beanFile;

    public FileGroupMapper(String workPath) {
        File file = new File(workPath, GROUP_PATH);
        FileIOUtil.mkDirs(file);
        this.beanFile = new BeanFile<>(file, FileGroupModel.class);
    }

    private FileGroupModel convert(GroupModel data) {
        return JsonUtil.convertObj(data, FileGroupModel.class);
    }

    private GroupModel reconvert(FileGroupModel data) {
        return JsonUtil.convertObj(data, GroupModel.class);
    }

    private FileGroupModel removeId(FileGroupModel data) {
        return BeanUtil.removeIdProp(data, FileGroupModel.class);
    }

    @Override
    public void insert(GroupModel data) {
        beanFile.insert(convert(data));
    }

    @Override
    public void insertAll(Collection<GroupModel> dataList) {
        List<FileGroupModel> modelList = dataList.stream()
                .map(this::convert)
                .collect(Collectors.toList());

        beanFile.insertAll(modelList);
    }

    @Override
    public void delete(Serializable id) {
        beanFile.deleteById(id);
    }

    @Override
    public void deleteAll(GroupModel data) {
        beanFile.delete(BeanUtil.getQueryWrapper(data));
    }

    @Override
    public void update(GroupModel data) {
        FileGroupModel groupModel = convert(data);
        beanFile.update(BeanUtil.getIdWrapper(groupModel), removeId(groupModel));
    }

    @Override
    public GroupModel selectOne(Serializable id) {
        return beanFile.selectById(id);
    }

    @Override
    public List<GroupModel> selectList(GroupModel data) {
        return beanFile.selectList(BeanUtil.getQueryWrapper(data))
                .stream()
                .map(this::reconvert)
                .collect(Collectors.toList());
    }

    @Override
    public List<GroupModel> selectList(Collection<? extends Serializable> id) {
        return beanFile.selectList(id)
                .stream()
                .map(this::reconvert)
                .collect(Collectors.toList());
    }
}
